import { Form, Select, Input, Button, Space, Modal, message } from 'antd'
import Typography from '@/views/components/Typography'
import EnlargeOrderModal from './EnlargeOrderModal';
import { useRef, useState, useEffect } from 'react';
import { useScanRegistrationStore } from '../../store';
import useUserStore from '@/stores/user.js'
import { find } from 'lodash';

const Filter = () => {
  const [form] = Form.useForm()
  const { pageConfig, isLoading, queryAfterSalesOrderList, resetState, orderList, updateState } = useScanRegistrationStore()
  const [expressNumber, setExpressModal] = useState('')
  const inputRef = useRef()
  const userInfo = useUserStore(state => state.userInfo);

  useEffect(() => {
    let timer
    if (expressNumber) {
      timer = setTimeout(() => {
        setExpressModal('')
      }, pageConfig.enlargeShowTime ? pageConfig.enlargeShowTime * 1000 : 5000)
    }
    return () => {
      timer && clearTimeout(timer)
    }
  }, [expressNumber])


  //扫码唯一码和商品编码时，如果已存在扫描出的数据就走绑定的逻辑
  const handleUpdateOrderList = (val) => {
    let btn = false;
    const arr = [...orderList];
    for (let i in arr) {
      const list = orderList[i].goodsList;
      const obj = find(list, ['sysSkuCode', val]);
      if (obj) {
        obj.uniqueCodes?.map(v => {
          v.selected = true;
        })
        btn = true;
        break;
      } else {
        for (let k in list) {
          const list1 = list[k].uniqueCodes || [];
          const obj1 = find(list1, ['value', val]);
          if (obj1 && !obj1.selected) {
            obj1.selected = true;
            btn = true;
            break;
          }
        }
      }
    }
    if (btn) {
      updateState({ orderList: arr });
    }
    form.setFieldValue('content', '');
  }

	// 阻止默认事件
	const prevent = e => {
		if (window.location.hash == "#/views/afterSales/scanRegistration") {
			if (["F1"].includes(e.key)) e.preventDefault();
		}
	};

  	// 键盘事件监听
	const scanRequest = e => {
		if (window.location.hash == "#/views/afterSales/scanRegistration") {
			const { key } = e;
			switch (key) {
				// case "Enter":
				// 	// 触发扫描请求
				// 	message.info("触发扫描请求", e);
				// 	break;
				case "F1":
					// 重置(F1)
          form.resetFields();
					resetState();
					break;
				default:
					break;
			}
		}
	};

  	//监听键盘事件,阻止默认事件
	useEffect(() => {
		window.addEventListener("keydown", prevent, false);
		window.addEventListener("keyup", scanRequest, false);
		return () => {
			window.removeEventListener("keydown", prevent, false);
			window.removeEventListener("keyup", scanRequest, false);
		};
	}, []);


  function handleSubmit(values) {
    if (!values.content) {
      return
    }

    if (values.type == 'uniqueCode' && orderList.length > 0) {
      handleUpdateOrderList(values.content);
      return;
    }
    queryAfterSalesOrderList({
      uuid: String(userInfo.uuid),
      logisticsNo: values.content,
      orderSn: values.content,
      outOrderSn: values.content,
      afterSaleSn: values.content,
      uniqueCode: values.content,
    }).then(res => {
      if (res.length) {
        form.setFieldValue('type', 'uniqueCode')
        form.setFieldValue('content', '')
        updateState({
          orderIdParameter: values.content
        })
      } else {
        message.warn('没有找到相关的售后单')
      }
    })
  }

  function showEmptyModal() {
    Modal.confirm({
      title: '提示',
      icon: false,
      content: <Typography as="s2" color="#333">未查询到对应退货物流信息，是否按照该物流创建无信息件售后单</Typography>,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {

      },
      onCancel: () => {
        form.resetFields()
      }
    });
  }

  const options = [
    // 快递单号、系统订单号、店铺订单号、售后单号、商品唯一码/商品编码
    { value: 'logisticsNo', label: '快递单号' },
    { value: 'orderSn', label: '系统订单号' },
    { value: 'outOrderSn', label: '店铺订单号' },
    { value: 'afterSaleSn', label: '售后单号' },
    { value: 'uniqueCode', label: '商品唯一码/商品编码' },
  ]

  return (
    <>
      <EnlargeOrderModal value={expressNumber} />
      <Form
        form={form}
        initialValues={{
          type: 'logisticsNo',
        }}
        wrapperCol={{ span: 24 }}
        size='large'
        onReset={() => {
          resetState()
        }}
        onFinish={handleSubmit}
        onValuesChange={(value) => {
          if (pageConfig.monitorShoot) {
            setExpressModal(value.content)
          }
        }}
      >
        <Form.Item
          name="type"
        >
          <Select options={options} onChange={() => {
            inputRef.current?.focus()
          }} />
        </Form.Item>

        <Form.Item name="content">
          <Input autoFocus placeholder="输入内容" ref={inputRef} />
        </Form.Item>
        <Form.Item style={{ marginBottom: 0 }}>
          <Space>
            <Button htmlType="reset"><Typography color="#4e5969" as="s2">重置(F1)</Typography></Button>
            <Button type="primary" htmlType="submit" loading={isLoading}>查询</Button>
          </Space>
        </Form.Item>
      </Form>
    </>
  )
}

export default Filter